//
//  NetworkTools+OAuth.swift
//  WeiBo
//
//  Created by 张德华 on 7/23/16.
//  Copyright © 2016 ZhangDeHua. All rights reserved.
//

import Foundation

extension WQNetworkTools {
    
    /**oAuth授权请求地址*/
    var oAuthURL: NSURL {
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectUri)"
        return NSURL(string: urlString)!
    }
    
    
    ///  加载access_token
    ///
    ///  - parameter code:     code 授权码
    ///  - parameter finished: finished 完成回调(字典)
    func loadAccesToken(code: String, finished: ([String: AnyObject]?) -> ()) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let params = ["client_id":appKey,
                      "client_secret":appSecret,
                      "grant_type":"authorization_code",
                      "code":code,
                      "redirect_uri":redirectUri]
        
        request(.POST, URLString: urlString, parameters: params) {(result) in
            
            guard let result = result,
                let access_token = result["access_token"] as? String,
                let uid = result["uid"] as? String else {
                    
                    print("数据格式不正确")
                    
                    finished(nil)
                    return
            }
            
            self.loadUser(access_token, uid: uid, finished: { (userDict) in
                
                guard var userDict = userDict else {
                    
                    print("用户数据加载错误")
                    finished(nil)
                    return
                }
                
                for (k,v) in result {
                    userDict[k] = v
                }
                
                ///------ 完成回调
                finished(userDict)
            })
            
        }
    }
}
